package asia.lxq.cic.aop;

import asia.lxq.cic.config.GlobalConfig;
import asia.lxq.cic.dao.AreaMapper;
import asia.lxq.cic.dao.GroupMapper;
import asia.lxq.cic.dao.UserMapper;
import asia.lxq.cic.entity.Result;
import asia.lxq.cic.entity.User;
import asia.lxq.cic.util.RedisUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class UserServiceAspect{

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AreaMapper areaMapper;
    @Autowired
    GroupMapper groupMapper;
    @Autowired
    UserMapper userMapper;

//    @Pointcut(value = "execution(* asia.lxq.cic.service.UserService.*(..))")
    @Pointcut(value = "@annotation(asia.lxq.cic.aop.NeedAop)")
    public void everyUpdate(){}

    @AfterReturning(value = "everyUpdate()",returning = "result")
    public void afterUpdate(Result<Object> result){
        if (result.getData() != null) {
            int userId=((User) result.getData()).getUserId();
            if (redisUtil.get(GlobalConfig.PRE_USERINFO_REDIS+userId)!=null){
                User userFromRedis=userMapper.selectById(userId);
                userFromRedis.setGroup(groupMapper.selectById(userFromRedis.getGroupId()));
                userFromRedis.query(areaMapper);
                redisUtil.set(GlobalConfig.PRE_USERINFO_REDIS+userFromRedis.getUserId(),userFromRedis);
            }
        }
    }
}
